package src;

/**
 * @author josbrsam
 * Simple UDP Server that receive and reply data to a client computer/thing.
 * The serverProtocol method is called each time a UDP packet arrive.
 *
 */


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;

public abstract class UDPServer extends DatagramSocket implements Runnable{

	private static final int MAX_PACKET_SIZE = 65535;
	private static final String CHARSETNAME = "utf-8";

	/**
	 * @throws SocketException
	 * @throws UnknownHostException
	 */
	public UDPServer() throws SocketException, UnknownHostException{
		super();
	}

	/**
	 * @param port Port to use
	 * @throws SocketException
	 * @throws UnknownHostException
	 */
	public UDPServer(int port) throws SocketException, UnknownHostException{
		super(port);
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		byte[] dataIn = new byte[MAX_PACKET_SIZE];
		byte[] dataOut;

		System.out.println("Starting Server on " + "port: " + this.getLocalPort());

		try {
			while(true){
				DatagramPacket in = new DatagramPacket(dataIn, dataIn.length);
				this.receive(in);

				InetAddress addr = in.getAddress();
				String dataStr = new String(in.getData(), 0, in.getLength(), CHARSETNAME);

				System.out.println(new Date().toString() + " Received: " + in.getLength() + " bytes, from: "  + addr.getHostAddress());

				//Fill dataOut buffer
				dataOut = serverProtocol(dataStr).getBytes();

				//Response
				DatagramPacket out = new DatagramPacket(dataOut, dataOut.length, in.getSocketAddress());
				this.send(out);

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		this.close();
	}

	/**
	 * @param inStr String received FROM client
	 * @return String to send TO client
	 */
	public abstract String serverProtocol(String inStr);
}
